package pr.iceworld.fernando.provideruser.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import pr.iceworld.fernando.gatecommon.service.impl.BizService;
import pr.iceworld.fernando.gatecommon.web.BaseController;
import pr.iceworld.fernando.gatecommon.web.result.WebBaseResult;
import pr.iceworld.fernando.provideruser.model.User;
import pr.iceworld.fernando.provideruser.repository.UserRepository;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RequestMapping("/users")
@Slf4j
@RestController
class UserController extends BaseController<BizService<UserRepository, User>, User> {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

//    @Autowired
//    private UserService userService;

    @GetMapping("/user/{username}")
    public WebBaseResult<User> getUserByUsername(@PathVariable("username") String username) {
        User user = new User();
        user.setUsername(username);
        User result = biz.selectOne(user);
        return new WebBaseResult<User>().success().data(result);
    }

    @GetMapping("/{id}")
    @ResponseBody
    protected WebBaseResult<User> get(@PathVariable String id) {
        return new WebBaseResult<User>().success().data(biz.selectByPrimaryKey(id));
    }

    @GetMapping("/findAll")
    public WebBaseResult<PageInfo<User>> findAll(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
            @RequestParam(value = "orderByValue", defaultValue = "create_time desc") String orderBy,
            @RequestParam(value = "dateStart") String dateStart,
            @RequestParam(value = "dateEnd") String dateEnd) {
        if (StringUtils.isEmpty(dateStart)) {
            dateStart = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ISO_LOCAL_DATE);
        }
        if (StringUtils.isEmpty(dateEnd)) {
            dateEnd = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
        }
        PageHelper.startPage(currentPage, pageSize, orderBy);
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        // Example 使用类属性而非数据库属性
        criteria.andBetween("createTime", dateStart, dateEnd);
        List<User> list = biz.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return new WebBaseResult().success().data(pageInfo);
    }
}
